import { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';

export const useNavigation = () => {
  const [activeMenu, setActiveMenu] = useState<string>('');
  const navigate = useNavigate();
  const location = useLocation();

  // 监听路由变化，更新activeMenu状态
  useEffect(() => {
    const path = location.pathname.split('/')[1];
    if (path === '' || path === 'home') {
      setActiveMenu('home');
    } else if (['bookmark', 'favorites', 'software', 'blog'].includes(path)) {
      setActiveMenu(path);
    } else {
      setActiveMenu('');
    }
  }, [location.pathname]);

  const handleMenuClick = (menuKey: string) => {
    setActiveMenu(menuKey);
    if (menuKey === 'home') {
      navigate('/');
    } else {
      navigate(`/${menuKey}`);
    }
  };

  const handleSubMenuClick = (e: any) => {
    const { key } = e;
    if (key.includes('-')) {
      const [parentKey, subKey] = key.split('-');
      navigate(`/${parentKey}/${subKey}`);
    } else {
      handleMenuClick(key);
    }
  };

  return {
    activeMenu,
    handleMenuClick,
    handleSubMenuClick,
    navigate,
    location,
  };
};
